package com.cjc.mAsyTack;

import java.io.IOException;

import android.content.Context;
import android.os.AsyncTask;

import com.cjc.tools.Constants;
import com.cjc.tools.JsonUtil;
import com.cjc.tools.RequestData;

/**
 ***************************************************** 
 * <hr>
 * <dt><span class="strong">类功能简介:</span></dt>
 * <dd>自定义异步数据请求类</dd>
 * <dd>注：执行该AsyncTask必须要有三个参数（暂时也只处理三个参数）</dd>
 * <dd>1、方法</dd>
 * <dd>2、参数</dd>
 * <dd>3、标志 （GET or POST）</dd>
 * <dt><span class="strong">创建时间:</span></dt>
 * <dd>2015-10-15 下午2:49:15</dd>
 * <dt><span class="strong">公司:</span></dt>
 * <dd>SHLD</dd>
 * 
 * @author aa1000777 - Email:aa1000777@qq.com
 * @param <T>
 * 
 ***************************************************** 
 */
public class MyAsyncTask<T> extends AsyncTask<String, Void, T> {
	private OnGetJsonResultListener mListener;// 回调接口
	private Class<?> mClz;
	private Context mContext;

	public MyAsyncTask(OnGetJsonResultListener listener, String className) {
		try {
			this.mClz = Class.forName(className);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		this.mListener = listener;
	}

	public MyAsyncTask(OnGetJsonResultListener listener, String className, Context context) {
		this.mListener = listener;
		try {
			this.mClz = Class.forName(className);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		this.mContext = context;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected T doInBackground(String... params) {
		String mMethod = params[0];// 方法
		String mParameter = params[1];// 参数
		String mFlag = params[2];// 标志 （GET or POST）
		String value = "";
		try {
			if (mFlag.equals(Constants.GET_JSON)) {
				if (mParameter != null) {
					value = RequestData.getJson(mMethod, mParameter);
				} else {
					value = RequestData.getJson(mMethod);
				}
			} else if (mFlag.equals(Constants.GET_JSON)) {
				value = RequestData.postJson(mMethod, mParameter);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		T mDatas = null;
		if (value != null && !"".equals(value)) {
			mDatas = (T) JsonUtil.readValue(value, this.mClz);
		}
		return mDatas;
	}

	@Override
	protected void onPostExecute(T string) {
		super.onPostExecute(string);
		// if (mContext != null) {
		// // 关闭Diallog
		// CommonFunction.closeDiallog();
		// }
		// 调用回调方法
		mListener.getJsonResult(string);
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		// if (mContext != null) {
		// // 启动Diallog
		// CommonFunction.showDialog(mContext);
		// }
	}
}
